JavaScript Essentials by Smashing Magazine

JavaScript Essentials by Smashing Magazine
Author: Smashing Magazine
Language: eng
Format: epub, mobi
Tags: Smashing eBooks
Published: 2012-10-25

You may have noticed that I didn’t include empty arrays in the list of falsies above. Empty arrays are curious things: they actually evaluate to truthy but, when compared against a boolean, behave like a falsy. Confused yet? With good cause. Another example perhaps?

var someVar = []; //empty array

alert(someVar == false); //evaluates true

if (someVar) alert('hello'); //alert runs, so someVar evaluates to true

To avoid coercion, you can use the value and type comparison operator, ===, (as opposed to ==, which compares only by value). So:

var someVar = 0;

alert(someVar == false); //evaluates true – zero is a falsy

alert(someVar === false); //evaluates false – zero is a number, not a boolean